package com.spotalog.shared.model;

import java.util.List;

import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlRootElement;

import lombok.Data;

import com.google.common.base.Preconditions;
import com.google.common.base.Splitter;
import com.google.common.collect.ImmutableList;

@Data
@XmlRootElement
@XmlAccessorType(XmlAccessType.FIELD)
public final class Location {
	public static final double MAX_LATITUDE = 90;
	public static final double MIN_LATITUDE = -90;
	public static final double MAX_LONGITUDE = 180;
	public static final double MIN_LONGITUDE = -180;

	private double latitude;
	private double longitude;

	public static Location valueOf(String commaDelimitedCoordinates) {
		List<String> coords = ImmutableList.copyOf(Splitter.on(",").split(
				commaDelimitedCoordinates));
		Preconditions
				.checkArgument(coords.size() >= 2,
						"Cannot create Location from [%s]! Must have 2 doubles (Lat-Lng)");
		double latitude = Double.valueOf(coords.get(0));
		double longitude = Double.valueOf(coords.get(1));
		return new Location(latitude, longitude);
	}

	/** For GWT Serialization */
	@SuppressWarnings("unused")
	private Location() {
	}

	public Location(double latitude, double longitude) {
		this.latitude = latitude < 0 ? Math.max(latitude, MIN_LATITUDE) : Math
				.min(latitude, MAX_LATITUDE);
		this.longitude = longitude < 0 ? Math.max(longitude, MIN_LONGITUDE)
				: Math.min(longitude, MAX_LONGITUDE);
	}
}